import React, { useState, useEffect } from 'react';
import { 
  Space, 
  Button, 
  Input, 
  message, 
  Popconfirm, 
  Tag, 
  Avatar, 
  Modal, 
  Drawer,
  Select,
  Form,
  Tabs
} from 'antd';
import { 
  SearchOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  LockOutlined, 
  UnlockOutlined,
  UserOutlined,
  KeyOutlined,
  UserDeleteOutlined
} from '@ant-design/icons';
import { FilterCard, TableCard } from '@/components/common';
import userService from '@/services/userService';
import { User, AdminType, ProblemPermission } from '@/types/user';
import UserDetail from './UserDetail';
import UserForm from './UserForm';
import ResetPasswordForm from './ResetPasswordForm';
import InvitationCodeManagement from './components/InvitationCodeManagement';

const { Option } = Select;

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [keyword, setKeyword] = useState('');
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [resetPasswordVisible, setResetPasswordVisible] = useState(false);
  const [resetPasswordUserId, setResetPasswordUserId] = useState<number | null>(null);
  const [activeTab, setActiveTab] = useState('users');

  // 加载用户列表
  const loadUsers = async (page = 1, search = '') => {
    setLoading(true);
    try {
      const response = await userService.getUsers(page, search);
      const { results, count } = response.data.data;
      setUsers(results);
      setTotal(count);
    } catch (error) {
      console.error('Failed to load users:', error);
      message.error('加载用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadUsers(currentPage, keyword);
  }, [currentPage]);

  // 处理搜索
  const handleSearch = () => {
    setCurrentPage(1);
    loadUsers(1, keyword);
  };

  // 处理页码变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 查看用户详情
  const handleViewUser = (user: User) => {
    setSelectedUser(user);
    setDetailVisible(true);
  };

  // 删除用户
  const handleDeleteUser = async (id: number) => {
    try {
      await userService.deleteUser(id);
      message.success('用户已删除');
      loadUsers(currentPage, keyword);
    } catch (error) {
      console.error('Failed to delete user:', error);
      message.error('删除用户失败');
    }
  };

  // 切换用户状态（禁用/启用）
  const handleToggleUserStatus = async (id: number) => {
    try {
      await userService.toggleUserStatus(id);
      message.success('用户状态已更新');
      loadUsers(currentPage, keyword);
    } catch (error) {
      console.error('Failed to toggle user status:', error);
      message.error('更新用户状态失败');
    }
  };

  // 创建用户
  const handleCreateUser = () => {
    setCreateModalVisible(true);
  };

  // 创建用户成功后的回调
  const handleUserCreated = () => {
    setCreateModalVisible(false);
    loadUsers(currentPage, keyword);
    message.success('用户创建成功');
  };

  // 用户详情更新后的回调
  const handleUserUpdated = () => {
    loadUsers(currentPage, keyword);
    message.success('用户信息已更新');
  };

  // 处理重置密码
  const handleResetPassword = (user: User) => {
    setResetPasswordUserId(user.id);
    setResetPasswordVisible(true);
  };

  // 密码重置成功的回调
  const handlePasswordResetSuccess = () => {
    setResetPasswordVisible(false);
    message.success('密码重置成功');
  };

  // 删除用户的个人资料
  const handleDeleteUserProfile = async (id: number) => {
    try {
      await userService.deleteUserProfile(id);
      message.success('用户个人资料已删除');
      loadUsers(currentPage, keyword);
    } catch (error: any) {
      console.error('Failed to delete user profile:', error);
      message.error(error.response?.data?.message || '删除用户个人资料失败');
    }
  };

  // 创建用户的个人资料
  const handleCreateUserProfile = async (id: number) => {
    try {
      await userService.createUserProfile(id);
      message.success('用户个人资料已创建');
      loadUsers(currentPage, keyword);
    } catch (error: any) {
      console.error('Failed to create user profile:', error);
      message.error(error.response?.data?.message || '创建用户个人资料失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text: string, record: User) => (
        <Space>
          <Avatar 
            src={record.userprofile ? userService.getAvatarUrl(record.userprofile.avatar) : undefined} 
            icon={<UserOutlined />}
          />
          <a onClick={() => handleViewUser(record)}>{text}</a>
        </Space>
      ),
    },
    {
      title: '真实姓名',
      dataIndex: ['userprofile', 'real_name'],
      key: 'real_name',
      render: (text: string, record: User) => (
        record.userprofile ? text : <Tag color="orange">未创建资料</Tag>
      ),
    },
    {
      title: '用户类型',
      dataIndex: 'admin_type',
      key: 'admin_type',
      render: (type: AdminType) => {
        let color = 'blue';
        if (type === 'Super Admin') {
          color = 'red';
        } else if (type === 'Admin') {
          color = 'purple';
        }
        return <Tag color={color}>{type}</Tag>;
      },
    },
    {
      title: '题目权限',
      dataIndex: 'problem_permission',
      key: 'problem_permission',
      render: (permission: ProblemPermission) => {
        let color = 'default';
        if (permission === 'All') {
          color = 'green';
        } else if (permission === 'Own') {
          color = 'cyan';
        }
        return <Tag color={color}>{permission}</Tag>;
      },
    },
    {
      title: '最后登录',
      dataIndex: 'last_login',
      key: 'last_login',
      render: (time: string) => time ? new Date(time).toLocaleString() : '从未登录',
    },
    {
      title: '状态',
      dataIndex: 'is_disabled',
      key: 'is_disabled',
      render: (disabled: boolean) => (
        <Tag color={disabled ? 'red' : 'green'}>
          {disabled ? '已禁用' : '正常'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleViewUser(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            icon={<KeyOutlined />}
            onClick={() => handleResetPassword(record)}
          >
            重置密码
          </Button>
          <Button
            type="link"
            icon={record.is_disabled ? <UnlockOutlined /> : <LockOutlined />}
            onClick={() => handleToggleUserStatus(record.id)}
            disabled={record.admin_type === 'Super Admin'}
          >
            {record.is_disabled ? '启用' : '禁用'}
          </Button>
          {record.userprofile ? (
            <Popconfirm
              title="确定要删除该用户的个人资料吗？此操作不可逆。"
              onConfirm={() => handleDeleteUserProfile(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                icon={<UserDeleteOutlined />}
                danger
              >
                删除资料
              </Button>
            </Popconfirm>
          ) : (
            <Popconfirm
              title="确定要为该用户创建个人资料吗？"
              onConfirm={() => handleCreateUserProfile(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                icon={<PlusOutlined />}
              >
                创建资料
              </Button>
            </Popconfirm>
          )}
          <Popconfirm
            title="确定要删除该用户吗？此操作不可逆。"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
            disabled={record.admin_type === 'Super Admin'}
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />}
              disabled={record.admin_type === 'Super Admin'}
            >
              删除用户
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={[
          {
            key: 'users',
            label: '用户管理',
            children: (
              <>
                <FilterCard
                  pageTitle="用户管理"
                  extra={
                    <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateUser}>
                      新建用户
                    </Button>
                  }
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <Input
                      placeholder="搜索用户名"
                      value={keyword}
                      onChange={(e) => setKeyword(e.target.value)}
                      onPressEnter={handleSearch}
                      prefix={<SearchOutlined />}
                      style={{ width: 300 }}
                    />
                    <Button type="primary" onClick={handleSearch}>
                      搜索
                    </Button>
                  </div>
                </FilterCard>

                <TableCard
                  tableProps={{
                    columns: columns,
                    dataSource: users,
                    rowKey: 'id',
                    loading: loading,
                    pagination: {
                      current: currentPage,
                      total: total,
                      pageSize: 20,
                      onChange: handlePageChange,
                      showSizeChanger: false,
                      showQuickJumper: true,
                      showTotal: (total) => `共 ${total} 个用户`,
                    },
                  }}
                />
              </>
            ),
          },
          {
            key: 'invitationCodes',
            label: '邀请码管理',
            children: <InvitationCodeManagement />,
          },
        ]}
      />

      {/* 用户详情抽屉 */}
      {selectedUser && (
        <UserDetail
          visible={detailVisible}
          user={selectedUser}
          onClose={() => setDetailVisible(false)}
          onUserUpdated={handleUserUpdated}
        />
      )}

      {/* 创建用户的模态框 */}
      <Modal
        title="创建新用户"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={700}
      >
        <UserForm onSuccess={handleUserCreated} />
      </Modal>

      {/* 重置密码的模态框 */}
      <Modal
        title="重置用户密码"
        open={resetPasswordVisible}
        onCancel={() => setResetPasswordVisible(false)}
        footer={null}
        width={500}
      >
        {resetPasswordUserId && (
          <ResetPasswordForm 
            userId={resetPasswordUserId} 
            onSuccess={handlePasswordResetSuccess}
            onCancel={() => setResetPasswordVisible(false)}
          />
        )}
      </Modal>
    </div>
  );
};

export default UserManagement; 